<template>
  <a-modal
    title="编辑设备"
    :width="800"
    :visible="visible"
    @cancel="handleCancel"
    @ok="handleSubmit"
    :confirmLoading="confirmLoading"
    :destroyOnClose="true"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item v-bind="formItemLayout" label="设备名称" hasFeedback>
          <a-input
            v-decorator="['node', { rules: [{ required: true, message: '设备名称不能为空' }] }]"
            :maxLength="64"
            placeholder="请输入设备名称"
            disabled="disabled"
          />
        </a-form-item>
        <a-form-item v-bind="formItemLayout" label="设备地址" hasFeedback>
          <a-input
            v-decorator="['node_alias', {initialValue: '', rules: []}]"
            :maxLength="64"
            placeholder="请输入设备地址"
            disabled="disabled"
          />
        </a-form-item>
        <a-form-item v-bind="formItemLayout" label="设备标签" hasFeedback>
          <a-input
            v-decorator="['dev_tag', { rules: [{ required: true, message: '设备标签不能为空' }] }]"
            :maxLength="64"
            placeholder="请输入设备标签"
            disabled="disabled"
          />
        </a-form-item>
        <a-form-item v-bind="formItemLayout" label="设备类型" hasFeedback>
          <a-select
            class="selectshow"
            show-search
            :default-active-first-option="false"
            style="width: 100%"
            v-decorator="['dev_type', {initialValue: ''}]"
            :show-arrow="false"
            allowClear
            mode="combobox"
            :autoClearSearchValue="true"
            placeholder="请选择设备类型"
          >
            <a-select-option v-for="(dev, index) in devTypeList" :key="index" :value="dev.name">{{ dev.name }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item v-bind="formItemLayout" label="设备型号" hasFeedback>
          <a-input
            v-decorator="['dev_model', {initialValue: '', rules: []}]"
            :maxLength="32"
            placeholder="请输入设备型号"
          />
        </a-form-item>
        <a-form-item v-bind="formItemLayout" label="设备厂商" hasFeedback>
          <a-select
            class="selectshow"
            show-search
            :default-active-first-option="false"
            style="width: 100%"
            v-decorator="['dev_vendor', {initialValue: ''}]"
            :show-arrow="false"
            allowClear
            mode="combobox"
            :autoClearSearchValue="true"
            placeholder="请选择设备厂商"
          >
            <a-select-option v-for="(vendor, index) in devVendorList" :key="index" :value="vendor.name">{{ vendor.name }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item v-bind="formItemLayout" label="序列号" hasFeedback>
          <a-input
            v-decorator="['dev_sn', {initialValue: '', rules: []}]"
            :maxLength="64"
            placeholder="请输入机器序列号"
          />
        </a-form-item>
        <a-form-item v-bind="formItemLayout" label="Rack" hasFeedback>
          <a-input
            v-decorator="['rack', { rules: [{ required: true, message: '机架位置(Rack)不能为空' }] }]"
            :maxLength="32"
            placeholder="请输入机架位置"
            disabled="disabled"
          />
        </a-form-item>
        <a-form-item v-bind="formItemLayout" label="U数" hasFeedback>
          <a-input
            v-decorator="['rack_u', {initialValue: '', rules: []}]"
            :maxLength="32"
            placeholder="请输入机架U数"
          />
        </a-form-item>
        <a-form-item v-bind="formItemLayout" label="数据中心" hasFeedback>
          <a-select
            class="selectshow"
            show-search
            :default-active-first-option="false"
            style="width: 100%"
            v-decorator="['location']"
            :show-arrow="false"
            allowClear
            mode="combobox"
            :autoClearSearchValue="true"
            placeholder="请选择数据中心"
          >
            <a-select-option v-for="(loc, index) in locList" :key="index" :value="loc.name">{{ loc.name }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item v-bind="formItemLayout" label="所属平台" hasFeedback>
          <a-select
            class="selectshow"
            show-search
            :default-active-first-option="false"
            style="width: 100%"
            v-decorator="['pcs_name']"
            :show-arrow="false"
            allowClear
            mode="combobox"
            :autoClearSearchValue="true"
            placeholder="请选择所属平台"
          >
            <a-select-option v-for="(pcs, index) in pcsList" :key="index" :value="pcs.name">{{ pcs.name }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item v-bind="formItemLayout" label="组织机构" hasFeedback>
          <a-select
            class="selectshow"
            show-search
            :default-active-first-option="false"
            style="width: 100%"
            v-decorator="['org_name']"
            :show-arrow="false"
            allowClear
            mode="combobox"
            :autoClearSearchValue="true"
            placeholder="请选择组织机构"
          >
            <a-select-option v-for="(org, index) in orgList" :key="index" :value="org.name">{{ org.name }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item v-bind="formItemLayout" label="纳管系统信息" hasFeedback>
          <a-select
            class="selectshow"
            show-search
            :default-active-first-option="false"
            style="width: 100%"
            v-decorator="['sub_system_name', {initialValue: ''}]"
            :show-arrow="false"
            allowClear
            mode="combobox"
            :autoClearSearchValue="true"
            placeholder="请选择纳管系统"
          >
            <a-select-option v-for="(sub, index) in subList" :key="index" :value="sub.name">{{ sub.name }}</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import { sqlSelect, sqlFindOne, sqlUpdate } from '@/api/sql'

export default {
  name: 'DevEditModal',

  data () {
    return {
      confirmLoading: false,
      visible: false,

      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 4 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 18 }
        }
      },

      form: this.$form.createForm(this),

      node: '',
      rack: '',
      dev_tag: '',
      result: {},

      /* 业务应用/所属平台/组织部门/数据中心/纳管系统列表: 动态 */
      appList: [],
      pcsList: [],
      orgList: [],
      locList: [],
      subList: []
    }
  },

  created () {
    /* 设备类型列表: 静态 */
    this.devTypeList = [
      { name: '服务器' },
      { name: '交换机' },
      { name: '路由器' },
      { name: '防火墙' },
      { name: '安全设备' },
      { name: '存储设备' }
    ]

    /* 设备厂商列表: 静态 */
    this.devVendorList = [
      { name: '华为' },
      { name: '联想' },
      { name: '安恒' },
      { name: '三所' }
    ]

    this.generateAppList()
    this.generatePcsList()
    this.generateOrgList()
    this.generateLocList()
    this.generateSubList()
  },

  computed: {
  },

  methods: {
    async init (node, nodeAlias, devTag, rack) {
      this.node = node
      this.node_alias = nodeAlias
      this.rack = rack
      this.dev_tag = devTag

      // 显示弹框
      this.visible = true
      this.result = await this.getByPrimaryKey(node, nodeAlias, devTag, rack)
      console.log('result', this.result)

      // 初始化form表单数据
      this.$nextTick(() => {
        this.form.setFieldsValue({
          node: this.result.node,
          node_alias: this.result.node_alias,
          dev_type: this.result.dev_type,
          dev_model: this.result.dev_model,
          dev_vendor: this.result.dev_vendor,
          dev_sn: this.result.dev_sn,
          dev_tag: this.result.dev_tag,
          rack: this.result.rack,
          rack_u: this.result.rack_u,
          pcs_name: this.result.pcs_name,
          org_name: this.result.org_name,
          location: this.result.location,
          sub_system_name: this.result.sub_system_name
        })
      })
    },

    async generateAppList () {
      this.data = await this.getAppList()
      const _this = this

      this.data.forEach(function (item) {
        _this.appList.push({
          'name': item.app_name
        })
      })
    },

    async generatePcsList () {
      this.data = await this.getPcsList()
      const _this = this

      this.data.forEach(function (item) {
        _this.pcsList.push({
          'name': item.pcs_name
        })
      })
    },

    async generateOrgList () {
      this.data = await this.getOrgList()
      const _this = this

      this.data.forEach(function (item) {
        _this.orgList.push({
          'name': item.org_name
        })
      })
    },

    async generateLocList () {
      this.data = await this.getLocList()
      const _this = this

      this.data.forEach(function (item) {
        _this.locList.push({
          'name': item.location_name
        })
      })
    },

    async generateSubList () {
      this.data = await this.getSubList()
      const _this = this

      this.data.forEach(function (item) {
        _this.subList.push({
          'name': item.sub_system_name
        })
      })
    },

    getAppList () {
      const params = {
        sql: `select * from cmdb.apps order by app_id asc`
      }
      return new Promise((resolve, reject) => {
        sqlSelect(params).then(
          (res) => {
            resolve(res)
          },
          (error) => {
            reject(error)
          }
        )
      })
    },

    getPcsList () {
      const params = {
        sql: `select * from cmdb.clouds order by pcs_id asc`
      }
      return new Promise((resolve, reject) => {
        sqlSelect(params).then(
          (res) => {
            resolve(res)
          },
          (error) => {
            reject(error)
          }
        )
      })
    },

    getOrgList () {
      const params = {
        sql: `select * from cmdb.orgs order by org_id asc`
      }
      return new Promise((resolve, reject) => {
        sqlSelect(params).then(
          (res) => {
            resolve(res)
          },
          (error) => {
            reject(error)
          }
        )
      })
    },

    getLocList () {
      const params = {
        sql: `select * from cmdb.locations order by location_id asc`
      }
      return new Promise((resolve, reject) => {
        sqlSelect(params).then(
          (res) => {
            resolve(res)
          },
          (error) => {
            reject(error)
          }
        )
      })
    },

    getSubList () {
      const params = {
        sql: `select * from cmdb.sub_system_info order by sub_system_id asc`
      }
      return new Promise((resolve, reject) => {
        sqlSelect(params).then(
          (res) => {
            resolve(res)
          },
          (error) => {
            reject(error)
          }
        )
      })
    },

    handleCancel () {
      // 取消弹框
      this.visible = false
    },

    handleSubmit () {
      const {
        form: { validateFields }
      } = this
      this.confirmLoading = true

      validateFields((errors, values) => {
        console.log('errors:', errors, 'val:', values)

        if (!errors) {
          this.verify(values.node, values.node_alias, values.dev_tag, values.rack).then((res) => {
            console.log(res)
            if (!res.node) {
              this.$notification['error']({
                message: '提示',
                description: '设备信息不存在'
              })
              this.confirmLoading = false
            } else {
              this.update(values).then((response) => {
                this.visible = false
                this.confirmLoading = false
                this.$notification['success']({
                  message: '提示',
                  description: '设备信息更新成功！'
                })

                // 延迟发送事件，解决列表刷新还是老数据的问题
                setTimeout(() => {
                  this.$emit('ok', values)
                }, 1000)
              })
            }
          })
        } else {
          this.confirmLoading = false
        }
      })
    },

    /*
     * 修改数据
     */
    update (values) {
      var params = {
        sql: `update cmdb.devices set node_alias='${values.node_alias}', dev_type='${values.dev_type}', dev_model='${values.dev_model}', dev_vendor='${values.dev_vendor}', dev_sn='${values.dev_sn}', dev_tag='${values.dev_tag}', rack='${values.rack}', rack_u='${values.rack_u}', pcs_name='${values.pcs_name}', org_name='${values.org_name}', location='${values.location}', sub_system_name='${values.sub_system_name}' where node='${this.result.node}' and node_alias='${this.result.node_alias}' and dev_tag='${this.result.dev_tag}' and rack='${this.result.rack}'`
      }
      return new Promise((resolve, reject) => {
        sqlUpdate(params).then(
          (res) => {
            resolve(res)
          },
          (error) => {
            reject(error)
          }
        )
      })
    },

    /*
     * 检查设备信息是否重复
     */
    verify (node, nodeAlias, devTag, rack) {
      const params = {
        sql: `select * from cmdb.devices where node='${node}' and node_alias='${nodeAlias}' and dev_tag='${devTag}' and rack='${rack}'`
      }
      return new Promise((resolve, reject) => {
        sqlFindOne(params).then(
          (res) => {
            resolve(res)
          },
          (error) => {
            reject(error)
          }
        )
      })
    },

    /*
     * 获取单条数据
     */
    getByPrimaryKey (node, nodeAlias, devTag, rack) {
      const params = {
        sql: `select * from cmdb.devices where node='${node}' and node_alias='${nodeAlias}' and dev_tag='${devTag}' and rack='${rack}'`
      }
      return new Promise((resolve, reject) => {
        sqlFindOne(params).then(
          (res) => {
            resolve(res)
          },
          (error) => {
            reject(error)
          }
        )
      })
    }
  }
}
</script>

<style lang="less" scoped>
</style>
